package com.chao.juc.thread;

/**
 * @author : Rookie
 * @description :
 * @date : 2023/9/24
 */
public class Print100 {

    private static final Object lock = new Object();

    private static int currThreadId = 1;

    private static int count = 0;
    private static final int MAX_COUNT = 100;

    public static void main(String[] args) {
        new Thread(new PrintTask(1))
                .start();
        new Thread(new PrintTask(2))
                .start();
    }

    public static class PrintTask implements Runnable {

        private final int threadId;

        public PrintTask(int threadId) {
            this.threadId = threadId;
        }

        @Override
        public void run() {
            while (count<MAX_COUNT) {
                synchronized (lock) {
                    while (threadId != currThreadId) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("线程" + currThreadId + "打印了" +count);
                    count++;
                    currThreadId = (currThreadId%2) +1;
                    lock.notifyAll();
                }
            }
        }
    }
}
